package com.fare.taluo.web.action;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JsonConfig;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.application.FreightPriceApplication;
import com.fare.taluo.application.crawl.TaskQueueLogApplication;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.application.plane.income.FreightPublishApplication;
import com.fare.taluo.core.domain.config.channel.SourceEntity;
import com.fare.taluo.core.domain.config.channel.SourceEntityRepository;
import com.fare.taluo.core.domain.config.channel.impl.SourceEntityRepositoryImpl;
import com.fare.taluo.core.domain.config.line.FlightInfoEntity;
import com.fare.taluo.helper.HbaseCustom;
import com.fare.taluo.util.DateJsonValueProcessor;
import com.fare.taluo.util.StringAndDateAndFileUtil;
import com.fare.taluo.vo.core.FreightPublishVO;
import com.fare.taluo.vo.core.PlaneInfo;
import com.fare.taluo.vo.core.PortEntityVO;
import com.fare.taluo.vo.core.SourceEntityVO;
import com.fare.taluo.vo.core.TaskRecordEntityVO;

@Controller("taskMonitoringAction")
@Scope("prototype")
public class TaskMonitoringAction extends BaseFdcAction{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6895790715397962649L;
	@Resource(name="taskQueueLogApplication")
	private TaskQueueLogApplication taskRecordApp;
	@Resource(name="sourceApplication")
	private SourceApplication sourceApp;
	@Resource(name="portApplication")
	private PortApplication portApp;
	@Resource(name="freightPriceApplication")
	private FreightPriceApplication freightPriceApplication;
	
	private  List<PlaneInfo>   allList;

	private List<PortEntityVO> portList;
	private List<SourceEntityVO> sourceList;
	private SourceEntityRepository sourceEntityRepository = new SourceEntityRepositoryImpl();
	
	private List<SourceEntityVO> uggsourceList;
	private List<TaskRecordEntityVO> taskRecordList;
	
	private String flightNumber; //航班号
	private String depCity; 	//起始城市
	private String fromCityCode; //起始城市三字码
	private String arrCity;		//终点城市
	private String toCityCode;// 目的城市三字码
	private String flightTime;   //航班时间
	private String grabChannel;	//渠道
	private String startTime;	//抓取时间段起始时间
	private String endTime;		//抓取时间段终止时间
	private  String carrier;    //航空公司
	@Resource(name="freightPublishApplication")
    private FreightPublishApplication freightPublishApplication ;
	private FreightPublishVO freightPublishVO;
	private String showData;
	
	public void init(){
		uggsourceList = sourceApp.findSourceEntityListByConditions("","","1","",1,1000);
		portList = portApp.findAllPortEntityVO();
		sourceList = sourceApp.findAllSourceEntity();
		
	}

	public String toTaskMonitoringJSP(){
		init();
		
		
		returnPageURL = "/fare/_taskmonitoring.jsp";
		return "dispatcher";
	}
	
	public void toQuerytoTaskMonitoringJSP() throws Exception{
		
		 allList =new ArrayList<PlaneInfo> () ;
		
		String fromCityStr = null;
		String toCityStr = null;
		String areaCity = null;
		String areastartTime,areaflightTime,areaendTime;
		
//		depCity=URLDecoder.decode(depCity, "utf-8");
//		arrCity=URLDecoder.decode(arrCity, "utf-8");
		grabChannel =URLDecoder.decode(grabChannel, "utf-8");
		carrier =URLDecoder.decode(carrier, "utf-8");
	    
		startTime = startTime;
		endTime = endTime;
		areastartTime = startTime.replace("-", "").replace(" ", "");
		areaflightTime = flightTime.replace("-", "");
		areaendTime = endTime.replace("-", "").replace(" ", ""); 	
	  
		
		if (StringAndDateAndFileUtil.checkString(fromCityCode) && StringAndDateAndFileUtil.checkString(toCityCode)) {
			//返回航段
			PortEntityVO vo = portApp.findCityNameByPortCode(fromCityCode);
			if(vo != null){
				fromCityStr = vo.getPortCode();
				areaCity = vo.getAreaCode(); 
			}
			PortEntityVO vo2 = portApp.findCityNameByPortCode(toCityCode);
			if(vo2 != null){
				toCityStr = vo2.getPortCode();
			}
		}
		areaCity = areaCity==null ? "" : String.format("%02d", Integer.parseInt(areaCity));
		if("航空公司官网".equals(grabChannel)){
			grabChannel =  String.format("%05d", Integer.parseInt(carrier));
		}else{
			
		}
		//航班时间
		List<String> flightTimes  =new ArrayList<String>();
		
		List<FlightInfoEntity> list;
		FlightInfoEntity en =new FlightInfoEntity();
		String startareaflightTime =null;
		String endareaflightTime = null;
		//判断航班号是否为空
		if(flightNumber.equals("")||flightNumber==null) {
			startareaflightTime =areaflightTime+"00";
			endareaflightTime =areaflightTime+"24";
		}else {
			list = en.findByFlightNo(flightNumber);
			if(list.size()!=0){
				for(int k =0;k<list.size();k++) {
					String time =list.get(k).getFlightStartTime().replace(":", "");
					startareaflightTime = areaflightTime+time.substring(0,2);
					endareaflightTime = startareaflightTime;
					flightTimes.add(endareaflightTime);
				}
			}
			
		}
		flightNumber = StringUtils.rightPad(flightNumber, 8, '0');
		String startflightNumber = null;
		String endflightNumber = null;
		if(flightNumber.equals("00000000")) {
			startflightNumber = "00000000";
			endflightNumber = "ZZZZZZZZ";
							   
		}else {
			startflightNumber = flightNumber;
			endflightNumber = flightNumber;
		}
		
	
		String timeKey;
		int count = 0;
		try {
			
			count = dealwithData(startTime,endTime);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String startKey;
		String endKey;
		   for (int i =0;i<=count;i++) {
			   List<PlaneInfo>   list1 = null;
			   ResultScanner rs = null;
			  
			
			if(flightNumber.equals("00000000")) {//航班为空时
				startKey = areastartTime+grabChannel+areaCity+fromCityStr+toCityStr+startareaflightTime+startflightNumber+"00000";
				endKey = areastartTime+grabChannel+areaCity+fromCityStr+toCityStr+endareaflightTime+endflightNumber+"ZZZZZ";
			
				try {
				//	list1 = freightPriceApplication.findByConditions("CRAWL_PLANE_FREIGHT", startKey, endKey);
					list1 = HbaseCustom.findByConditionsToPlaneInfo(HbaseCustom.CRAWL_PLANE_FREIGHT, startKey, endKey);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(list1.size()!=0) {
					for(int j=0;j<list1.size();j++) {
						if(list1.get(j)!=null) {
							allList.add(list1.get(j));
						}
					}
				}
			}else {
				for(int h =0;h<flightTimes.size();h++) {
//					startKey = areastartTime+grabChannel+areaCity+fromCityStr+toCityStr+flightTimes.get(h)+startflightNumber+"00000";
//					endKey = areastartTime+grabChannel+areaCity+fromCityStr+toCityStr+flightTimes.get(h)+endflightNumber+"ZZZZZ";
					startKey = grabChannel+areastartTime+areaCity+fromCityStr+toCityStr+flightTimes.get(h)+startflightNumber+"00000";
					endKey = grabChannel+areastartTime+areaCity+fromCityStr+toCityStr+flightTimes.get(h)+endflightNumber+"ZZZZZ";
					list1  = HbaseCustom.findByConditionsToPlaneInfo(HbaseCustom.CRAWL_PLANE_FREIGHT, startKey, endKey);
					if(list1.size()!=0) {
						for(int j=0;j<list1.size();j++) {
							if(list1.get(j)!=null) {
								allList.add(list1.get(j));
							}
						}
					}
				}

			}
			try {
			    timeKey = addoneHours(startTime);
			    startTime = timeKey;
				areastartTime = timeKey.replace("-", "").replace(" ", "");	
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		
			}
				if(allList!=null){//查找到数据 
					
					JsonConfig jsonConfig = new JsonConfig();
					jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
					freightPublishVO = freightPublishApplication.findByLine(fromCityStr, toCityStr);
					
					String stardardPrice = null;
					if(freightPublishVO==null){
						logger.error("该航线没有标准运价，请再次配置!");
						stardardPrice = "1";
					}else{
						stardardPrice =  ""+freightPublishVO.getStandardPrice();
					}
					
					
					String jsonStr = "{\"Total\":"+allList.size()+","+ "\"Rows\":"+com.fare.taluo.util.JsonUtil.toJson(allList)+"}";
					
					
					data = "{\"json\":"+jsonStr+","+ "\"standardPrice\":"+stardardPrice+"}";
				}
				super.toJSONOut(data);
		
	
	}
	
	public int dealwithData(String startTime,String endTime) throws Exception{
		
		 //计算两个时间相差几小时，
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
		java.util.Date now = df.parse(startTime);
		java.util.Date old =df.parse(endTime);
		long l=old.getTime()-now.getTime();
		int hour=(int) (l/(60*60*1000));
//		System.out.println("相差："+hour+"小时");
		
		return hour;
		
	}
	
	public String  addoneHours(String time) throws Exception{
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
		java.util.Date date = df.parse(time);
		Calendar begin=Calendar.getInstance();
		begin.setTime(date);//给定起始时间
		begin.add(Calendar.HOUR,1);//增加了一小时
		String times =df.format(begin.getTime());
//		System.out.println(df.format(begin.getTime()));
		
		return times;
	}
	
	private String getSourceEntityHbKeyByName(String name) {
		String key = null;
		try {
			SourceEntity se = sourceEntityRepository
					.getSourceEntityByName(name);
			if (se != null) {
			//	System.out.println(se.getHbaseKey());
				key = se.getHbaseKey();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return key;
	}
	private String data;
	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}
	public String getFlightNumber() {
		return flightNumber;
	}

	public void setFlightNumber(String flightNumber) {
		this.flightNumber = flightNumber;
	}

	
	public TaskQueueLogApplication getTaskRecordApp() {
		return taskRecordApp;
	}
	
	public void setTaskRecordApp(TaskQueueLogApplication taskRecordApp) {
		this.taskRecordApp = taskRecordApp;
	}

	public List<SourceEntityVO> getUggsourceList() {
		return uggsourceList;
	}
	
	public void setUggsourceList(List<SourceEntityVO> uggsourceList) {
		this.uggsourceList = uggsourceList;
	}
	public SourceApplication getSourceApp() {
		return sourceApp;
	}

	public void setSourceApp(SourceApplication sourceApp) {
		this.sourceApp = sourceApp;
	}

	public PortApplication getPortApp() {
		return portApp;
	}

	public void setPortApp(PortApplication portApp) {
		this.portApp = portApp;
	}
	public String getDepCity() {
		return depCity;
	}

	public void setDepCity(String depCity) {
		this.depCity = depCity;
	}

	public String getArrCity() {
		return arrCity;
	}

	public void setArrCity(String arrCity) {
		this.arrCity = arrCity;
	}

	public String getFlightTime() {
		return flightTime;
	}

	public void setFlightTime(String flightTime) {
		this.flightTime = flightTime;
	}

	public List<PortEntityVO> getPortList() {
		return portList;
	}

	public void setPortList(List<PortEntityVO> portList) {
		this.portList = portList;
	}

	public List<SourceEntityVO> getSourceList() {
		return sourceList;
	}

	public void setSourceList(List<SourceEntityVO> sourceList) {
		this.sourceList = sourceList;
	}

	public List<TaskRecordEntityVO> getTaskRecordList() {
		return taskRecordList;
	}

	public void setTaskRecordList(List<TaskRecordEntityVO> taskRecordList) {
		this.taskRecordList = taskRecordList;
	}

	

	public String getGrabChannel() {
		return grabChannel;
	}

	public void setGrabChannel(String grabChannel) {
		this.grabChannel = grabChannel;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	

	public String getShowData() {
		return showData;
	}

	public void setShowData(String showData) {
		this.showData = showData;
	}
	public String getCarrier() {
		return carrier;
	}

	public void setCarrier(String carrier) {
		this.carrier = carrier;
	}
	public String getFromCityCode() {
		return fromCityCode;
	}

	public void setFromCityCode(String fromCityCode) {
		this.fromCityCode = fromCityCode;
	}

	public String getToCityCode() {
		return toCityCode;
	}

	public void setToCityCode(String toCityCode) {
		this.toCityCode = toCityCode;
	}

}
